const router = require("koa-router")();

const UUID = require('uuid')

const ArticleBasic = require('../../model/ArticleBasic');  // 文章详情数据
const UserRelation = require('../../model/UserRelation')
const ArticleCollect = require('../../model/ArticleCollect')
const ArticleAttitude = require('../../model/ArticleAttitude')
const ArticleComment = require('../../model/ArticleComment')
const UserRead = require('../../model/UserRead')
const sd = require('silly-datetime')
const axios = require('axios')
const url = 'http://ttapi.research.itcast.cn/app/v1_0/articles/'

const { getUserIdByContext, getBlackArticleIdList, getImage, getDefaultMan } = require('../token')

// 获取文章列表

router.get('/', async ctx => {
  let { channel_id, timestamp } = ctx.request.query
  if ((!channel_id && channel_id != 0 ) || !timestamp) {
      return { success: false, status: 400, message: '频道id或者时间戳参数缺失' }
  }
  if (channel_id == 0) {
    // 如果是推荐 就随机找一个频道
    channel_id = '11'
  }
  const user_id = await getUserIdByContext(ctx) 
  const list = user_id ? await getBlackArticleIdList(user_id): []
  ctx.status = 200
  return  { data: (await getList(channel_id, timestamp, list )) } 
})

// 获取列表内容
const  getList = async (channel_id, timestamp, list ) => {
// 获取思路  时间戳  => redis缓存查找对应的时间, 找到之后, 获取对应的数量, 进行分页获取
  // 如果找不到数量 认为是最新的数据 则获取最新的数据  同时 生成下一个时间戳 返回 存入redis数量， 同时销毁前数量
  const pageSize = 10 // 每页获取数量
  let pre_timestamp = null // 下一个时间戳
  let results = await ArticleBasic.aggregate([{
    $lookup: {
      from: "user_basic",
      localField: "user_id",
      foreignField: "user_id",
      as: "user"
    }
  },{
    $match:  {
      channel_id, // 筛选条件
      update_time: { $lt: timestamp }, // 筛选出小于等于此时间的数据
      article_id:  { $nin: list } 
    } 
  }, { 
    // 倒序排列
    $sort: {
      update_time: -1
    }
   }, {
    $limit: pageSize // 限制数量
  }])
  if (results.length < pageSize) {
    // 如果找不到对应的数据
    pre_timestamp = null  // 返回时间戳为null  表示 没有数据了
  }else {
    pre_timestamp = results[results.length - 1].update_time // 获取前一个时间戳
  }
  results = results.map(item => ({
    art_id: item.article_id ,
    title: item.title,
    aut_id: item.user_id,
    comm_count: item.comment_count,
    pubdate: item.create_time,
    aut_name: item.user && item.user.length ? item.user[0].user_name : '无名氏',
    is_top: 0,
    cover: item.cover && item.cover.split(',').length ? { type: item.cover.split(',').length, images: item.cover.split(',')  } :{ type: 0 }
  }))  
  return  {
    results, 
    pre_timestamp
  }
}
// 获取新闻文章详情
router.get('/:article_id', async ctx => {
   const { article_id } = ctx.params
   const user_id = await getUserIdByContext(ctx) // 获取用户id
   if (!article_id) {
     return  { success: false, message: '文章id不能为空'  }
   }
   if (article_id.startsWith('l-')) {
     // 如果id以1-为起始, 说明这个id是线上的数据 从搜索过来的
     // 搜索线上的数据

     let art_id = article_id.substr(2)
    const { data: { data } } =  await axios({ url: `${url}${art_id}` })
    const man = getDefaultMan() // 线上数据的默认人昵称
    let attidude = await ArticleAttitude.findOne({ article_id, user_id }).lean()
    attidude = attidude || null
    const userFollows = await UserRelation.find({ user_id, target_user_id: '1111' }).lean()

    let comments = await ArticleComment.find({ article_id }).lean()
    comments = comments || []
    return { data: { ...data, ...man, 
      attitude: attidude ? attidude.attidude : -1,
      comm_count: comments.length,
      is_followed: !!userFollows.length,    // 是否关注了作者
    } }
   }
 const resultList =  await ArticleBasic.aggregate([{
     $lookup: {
      from: "news_article_content",
      localField: "article_id",
      foreignField: "article_id",
      as: "articleInfo"
     }
   }, {
    $lookup: {
      from: "user_basic",
      localField: "user_id",
      foreignField: "user_id",
      as: "userInfo",
     }
   },{
    $lookup: {
      from: "news_attitude",
      localField: "article_id",
      foreignField: "article_id",
      as: "attitudeInfo"
     }
   },{
     $match: {
      article_id
     }, 
   },{
    $limit: 1
  }])
// 记录阅读历史
 if (user_id) {
   const findOne = await UserRead.findOne({ user_id, article_id }).lean()
   if (findOne) {
     // 更新阅读历史的时间
    await UserRead.findOneAndUpdate(findOne, { update_time: sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')  })
   }else {
     // 插入阅读历史
    await UserRead.create({ user_id, read_id: UUID.v4(), article_id  })
   }
 }  
   if (resultList && resultList.length) {
      // 增加阅读次数
    const userFollows = await UserRelation.find({ user_id }).lean()
     const result = resultList[0]
     await ArticleBasic.findOneAndUpdate({ article_id }, { read_count: (result.read_count ? result.read_count + 1 : 1)  })

     const attitude = result.attitudeInfo.find(item => item.user_id === user_id )
     const is_collected = !! (await ArticleCollect.find({ user_id, article_id }).countDocuments())
     return { 
       data: {
        art_id: result.article_id,
        title: result.title,
        pubdate: result.create_time,
        aut_id: result.user_id,
        content: result.articleInfo && result.articleInfo.length ? result.articleInfo[0].content : '' ,
        aut_name: result.userInfo && result.userInfo.length ? result.userInfo[0].user_name : '黑马先锋',
        aut_photo : result.userInfo && result.userInfo.length ? getImage(result.userInfo[0].profile_photo): getImage() ,
        is_followed: userFollows.some(item => item.target_user_id === result.user_id),    // 是否关注了作者
        is_collected: is_collected, // 是否收藏了文章
        attitude: attitude ? attitude.attitude : -1, // 对文章的态度
        comm_count: result.comment_count,
        read_count: result.read_count, // 阅读数量
        like_count:  result.attitudeInfo.filter(item => item.attitude == 1).length // 点赞数
       }
     }
   } 
   ctx.status = 200
   return  { status: 404, message: '查找不到对应的文章' }
})

module.exports = router.routes();

// 时间戳